package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 检查用户是否完成登录
 */
@Slf4j
@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路径匹配器
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //强制类型转换是为了使用子类特有的方法
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //1. 获取本次请求的url
        final String requestURI = request.getRequestURI();
        log.info("拦截到请求:{}", requestURI);
        //2.定义不需要处理的的请求的路径
        String[] urls = new String[]{"/employee/login", "/backend/**", "/front/**", "/common/**", "/user/sendMsg", "/user/login","/doc.html","/webjars/**","/swagger-resources","/v2/api-docs"};
        //3.判断本次请求是否需要处理
        boolean check = check(urls, requestURI);
        //4.如果不需要处理,直接放行
        if (check) {
            log.info("本次请求{}不需要处理", requestURI);
            chain.doFilter(request, response);
            return;
        }

        if (request.getSession().getAttribute("employee") != null) {
            log.info("用户已登录，用户id为：{}", request.getSession().getAttribute("employee"));
            chain.doFilter(request, response);
            return;
        }
        //客户端判断登录转态,如果已登录，则直接放行
        final Object user = request.getSession().getAttribute("user");
        if (user!=null){
            chain.doFilter(request, response);
            return;
        }

        //如果未登录
        log.info("用户未登录");
        //不是controller,返回对象的实收需要转换成json对象那个
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));


    }

    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
